This article was published as a part of the Data Science Blogathon
In the last blog we looked at a test to find out correlation between the continuous variable in our data which you can read here. In this blog we will take a look at an important test that we can conduct to find out the correlation between the categorical variables in our data is Chi-Square Test, I will try to make the blog easy to understand focusing more on the implementation rather than the theory behind the test in this blog we will be looking at topics like:
Chi-Square test is a statistical test which is used to find out the difference between the observed and the expected data we can also use this test to find the correlation between categorical variables in our data. The purpose of this test is to determine if the difference between 2 categorical variables is due to chance, or if it is due to a relationship between them.
It is important to note that the variables to be compared should have only 2 categories i.e 1 and 0 the chi-square test fails to determine the correlation between variables with more than 2 categories.
While conducting the chi-square test we have to initially consider 2 hypothesis i.e the Null Hypothesis and the Alternate Hypothesis.
Now, if the p-value obtained after conducting the test is less than 0.05 we reject the Null hypothesis and accept the Alternate hypothesis and if the p-value is greater that 0.05 we accept the Null hypothesis and reject the Alternate hypothesis. Now, let’s move onto the implementation. If you want to know more about the theory behind the Chi-square test you can check this out.
To implement the chi-square test in python the easiest way is using the chi2 function in the sklearn.feature_selection. The function takes in 2 parameters which are:
The function returns 2 arrays containing the chi2 statistics and p_values.
We will be using the p_values to determine the dependency of the variables. In the example below I have used a sample dataset which has 3 columns namely Gender, Smoking, Drinking the values of these columns have been initialised randomly. The dataset can be found on my Github repository here. Now our Null hypothesis will be that the variables being compared are independent and our alternate hypothesis will be that the variables are independent.from sklearn.feature_selection import chi2 import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # Load Dataset df = pd.read_csv(‘SampleData.csv’) # Resultant Dataframe will be a dataframe where the column names and Index will be the same # This is a matrix similar to correlation matrix which we get after df.corr() # Initialize the values in this matrix with 0 resultant = pd.DataFrame(data=[(0 for i in range(len(df.columns))) for i in range(len(df.columns))], columns=list(df.columns)) resultant.set_index(pd.Index(list(df.columns)), inplace = True) # Finding p_value for all columns and putting them in the resultant matrix for i in list(df.columns): for j in list(df.columns): if i != j: chi2_val, p_val = chi2(np.array(df[i]).reshape(-1, 1), np.array(df[j]).reshape(-1, 1)) resultant.loc[i,j] = p_val print(resultant)
In the above code it can be observed that the p-values between the same columns are not calculated (Line 21), this is because we know that the correlation between same columns is going to be very high which will fetch us a value very close to 0. The code above will print a data frame that will look like the image below. Now that we have the results we will move onto visualizing the data frame.
Now that we have the data-frame will use the Heat map to plot the graph similar to the heat map used for visualising Pearson correlation. For this we will use the seaborn library. The code for visualization is as shown below-# Plotting a heatmap fig = plt.figure(figsize=(6,6)) sns.heatmap(resultant, annot=True, cmap=’Blues’) plt.title(‘Chi-Square Test Results’) plt.show()
The result produced by the above code will be as represented in the figure below now, using this heat map we can easily interpret the outcome of the test.
In this blog, we have seen what is chi-square test? What is it used for? How to implement the test in python? And finally how to visualize the result? If you have any suggestions or questions feel free to comment them down. Also, connect with me on LinkedIn. Happy Learning! In future blogs I will try to cover other statistical tests like the T-test and the Anova test.
Connect with me on LinkedIn
Email: [email protected]
Check out my previous articles here.
The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion.
You can use libraries in Python such as SciPy or Statsmodels to perform a Chi-Square Test. These libraries provide functions to calculate the test statistic and p-value, facilitating easy implementation.
The Chi-Square Test is appropriate for categorical data, where observations fall into different categories. It is commonly used to analyze relationships between categorical variables.
Yes, you can visualize Chi-Square Test results using various Python libraries such as Matplotlib or Seaborn. These libraries allow you to create visual representations like bar charts or heatmaps to enhance the interpretation of your findings.
What is a Chi-Square Test? Formula, Examples &a...
Parametric and Non-Parametric Tests: The Comple...
Discovering Insights with Chi Square Tests: A H...
How to Use Chi Square to Fuel A/B Test?
Feature Selection using Statistical Tests
Statistical Effect Size and Python Implementation
Intermediate Statistical Concepts for Data Scie...
How to select Best Split in Decision Trees usin...
Implementation of Decision Tree Using Chi_Squar...
Comprehensive Guide on Non Parametric Tests
We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.
Show details
This site uses cookies to ensure that you get the best experience possible. To learn more about how we use cookies, please refer to our Privacy Policy & Cookies Policy.
It is needed for personalizing the website.
Expiry: Session
Type: HTTP
This cookie is used to prevent Cross-site request forgery (often abbreviated as CSRF) attacks of the website
Expiry: Session
Type: HTTPS
Preserves the login/logout state of users across the whole site.
Expiry: Session
Type: HTTPS
Preserves users' states across page requests.
Expiry: Session
Type: HTTPS
Google One-Tap login adds this g_state cookie to set the user status on how they interact with the One-Tap modal.
Expiry: 365 days
Type: HTTP
Used by Microsoft Clarity, to store and track visits across websites.
Expiry: 1 Year
Type: HTTP
Used by Microsoft Clarity, Persists the Clarity User ID and preferences, unique to that site, on the browser. This ensures that behavior in subsequent visits to the same site will be attributed to the same user ID.
Expiry: 1 Year
Type: HTTP
Used by Microsoft Clarity, Connects multiple page views by a user into a single Clarity session recording.
Expiry: 1 Day
Type: HTTP
Collects user data is specifically adapted to the user or device. The user can also be followed outside of the loaded website, creating a picture of the visitor's behavior.
Expiry: 2 Years
Type: HTTP
Use to measure the use of the website for internal analytics
Expiry: 1 Years
Type: HTTP
The cookie is set by embedded Microsoft Clarity scripts. The purpose of this cookie is for heatmap and session recording.
Expiry: 1 Year
Type: HTTP
Collected user data is specifically adapted to the user or device. The user can also be followed outside of the loaded website, creating a picture of the visitor's behavior.
Expiry: 2 Months
Type: HTTP
This cookie is installed by Google Analytics. The cookie is used to store information of how visitors use a website and helps in creating an analytics report of how the website is doing. The data collected includes the number of visitors, the source where they have come from, and the pages visited in an anonymous form.
Expiry: 399 Days
Type: HTTP
Used by Google Analytics, to store and count pageviews.
Expiry: 399 Days
Type: HTTP
Used by Google Analytics to collect data on the number of times a user has visited the website as well as dates for the first and most recent visit.
Expiry: 1 Day
Type: HTTP
Used to send data to Google Analytics about the visitor's device and behavior. Tracks the visitor across devices and marketing channels.
Expiry: Session
Type: PIXEL
cookies ensure that requests within a browsing session are made by the user, and not by other sites.
Expiry: 6 Months
Type: HTTP
use the cookie when customers want to make a referral from their gmail contacts; it helps auth the gmail account.
Expiry: 2 Years
Type: HTTP
This cookie is set by DoubleClick (which is owned by Google) to determine if the website visitor's browser supports cookies.
Expiry: 1 Year
Type: HTTP
this is used to send push notification using webengage.
Expiry: 1 Year
Type: HTTP
used by webenage to track auth of webenagage.
Expiry: Session
Type: HTTP
Linkedin sets this cookie to registers statistical data on users' behavior on the website for internal analytics.
Expiry: 1 Day
Type: HTTP
Use to maintain an anonymous user session by the server.
Expiry: 1 Year
Type: HTTP
Used as part of the LinkedIn Remember Me feature and is set when a user clicks Remember Me on the device to make it easier for him or her to sign in to that device.
Expiry: 1 Year
Type: HTTP
Used to store information about the time a sync with the lms_analytics cookie took place for users in the Designated Countries.
Expiry: 6 Months
Type: HTTP
Used to store information about the time a sync with the AnalyticsSyncHistory cookie took place for users in the Designated Countries.
Expiry: 6 Months
Type: HTTP
Cookie used for Sign-in with Linkedin and/or to allow for the Linkedin follow feature.
Expiry: 6 Months
Type: HTTP
allow for the Linkedin follow feature.
Expiry: 1 Year
Type: HTTP
often used to identify you, including your name, interests, and previous activity.
Expiry: 2 Months
Type: HTTP
Tracks the time that the previous page took to load
Expiry: Session
Type: HTTP
Used to remember a user's language setting to ensure LinkedIn.com displays in the language selected by the user in their settings
Expiry: Session
Type: HTTP
Tracks percent of page viewed
Expiry: Session
Type: HTTP
Indicates the start of a session for Adobe Experience Cloud
Expiry: Session
Type: HTTP
Provides page name value (URL) for use by Adobe Analytics
Expiry: Session
Type: HTTP
Used to retain and fetch time since last visit in Adobe Analytics
Expiry: 6 Months
Type: HTTP
Remembers a user's display preference/theme setting
Expiry: 6 Months
Type: HTTP
Remembers which users have updated their display / theme preferences
Expiry: 6 Months
Type: HTTP
Used by Google Adsense, to store and track conversions.
Expiry: 3 Months
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
These cookies are used for the purpose of targeted advertising.
Expiry: 6 Hours
Type: HTTP
These cookies are used for the purpose of targeted advertising.
Expiry: 1 Month
Type: HTTP
These cookies are used to gather website statistics, and track conversion rates.
Expiry: 1 Month
Type: HTTP
Aggregate analysis of website visitors
Expiry: 6 Months
Type: HTTP
This cookie is set by Facebook to deliver advertisements when they are on Facebook or a digital platform powered by Facebook advertising after visiting this website.
Expiry: 4 Months
Type: HTTP
Contains a unique browser and user ID, used for targeted advertising.
Expiry: 2 Months
Type: HTTP
Used by LinkedIn to track the use of embedded services.
Expiry: 1 Year
Type: HTTP
Used by LinkedIn for tracking the use of embedded services.
Expiry: 1 Day
Type: HTTP
Used by LinkedIn to track the use of embedded services.
Expiry: 6 Months
Type: HTTP
Use these cookies to assign a unique ID when users visit a website.
Expiry: 6 Months
Type: HTTP
These cookies are set by LinkedIn for advertising purposes, including: tracking visitors so that more relevant ads can be presented, allowing users to use the 'Apply with LinkedIn' or the 'Sign-in with LinkedIn' functions, collecting information about how visitors use the site, etc.
Expiry: 6 Months
Type: HTTP
Used to make a probabilistic match of a user's identity outside the Designated Countries
Expiry: 90 Days
Type: HTTP
Used to collect information for analytics purposes.
Expiry: 1 year
Type: HTTP
Used to store session ID for a users session to ensure that clicks from adverts on the Bing search engine are verified for reporting purposes and for personalisation
Expiry: 1 Day
Type: HTTP
Cookie declaration last updated on 24/03/2023 by Analytics Vidhya.
Cookies are small text files that can be used by websites to make a user's experience more efficient. The law states that we can store cookies on your device if they are strictly necessary for the operation of this site. For all other types of cookies, we need your permission. This site uses different types of cookies. Some cookies are placed by third-party services that appear on our pages. Learn more about who we are, how you can contact us, and how we process personal data in our Privacy Policy.
Edit
Resend OTP
Resend OTP in 45s
I have a set of data with uncertainties involved x ,y. I fitted this x ,y as straight line by least square method so I have a equation like y=2x+1. How can I calculate the chi-square of this fitting Please help me.